package com.cy.flyweight;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * <br>@class: FlyweightTest
 * <br>@description: 享元模式
 * <br>@author: cy
 * <br>@date: 2020-03-29 13:41:51
 * <br>@version: 1.0
 * <br>
 * <br>@since: (版本) 作者 时间 注释
 */
public class FlyweightTest {
    public static void main(String[] args) {
        //运用共享技术有效地支持大量细粒度的对象
        //应用最广的 是 String 对象
        new Thread(()->{
            TreeNode treeNode = null;
            //Lambda
            for (int i = 0; i <10 ; i++) {
                treeNode = new TreeNode(3+i,5+i,TreeFactory.buildTree("杨树",5,1,0));
                treeNode = new TreeNode(4+i,7+i,TreeFactory.buildTree("松树",3,1,1));
            }
        }).start();
        new Thread(()->{
            TreeNode treeNode = null;
            //Lambda
            for (int i = 0; i <10 ; i++) {
                treeNode = new TreeNode(3+i,5+i,TreeFactory.buildTree("杨树",5,1,0));
                treeNode = new TreeNode(4+i,7+i,TreeFactory.buildTree("松树",3,1,1));
                treeNode = new TreeNode(1+i,2+i,TreeFactory.buildTree("柳树",3,1,1));
            }
        }).start();

    }
}
class TreeFactory{
    private static Map<String,Tree> map = new ConcurrentHashMap();
    public static  Tree buildTree(String name,Integer height, Integer weight, int color){
        synchronized(map){
            if (map.containsKey(name)) {
                return map.get(name);
            }
            Tree tree = new Tree(name,height,weight,color);
            map.put(name,tree);
            return  tree;
        }
    }
}
class TreeNode{
    private int x;
    private int y;
    private Tree tree;

    public TreeNode(int x, int y, Tree tree) {
        this.x = x;
        this.y = y;
        this.tree = tree;
    }
}
class Tree {
    private final String name;
    private final Integer height;
    private final Integer weight;
    private final int color;

    public Tree(String name, Integer height, Integer weight, int color) {
        this.name = name;
        this.height = height;
        this.weight = weight;
        this.color = color;
        System.out.println(name+" The tree is build");
    }

    public String getName() {
        return name;
    }

    public Integer getHeight() {
        return height;
    }

    public Integer getWeight() {
        return weight;
    }

    public int getColor() {
        return color;
    }
}
